﻿using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;


namespace RayDen.Library.Data
{
    public interface ICache
    {
        void Set<TValue>(TValue val, string name);
        TValue Get<TValue>(string name, TValue @default);
    }

    public class FileCache : ICache
    {
        private Dictionary<string, object> items;
        private string cacheDir;

        public FileCache(string dir)
        {
            cacheDir = dir;
            items = new Dictionary<string, object>();
        }

        public void Merge(IDictionary<string, object> objects)
        {
            foreach (var obj in objects)
            {
                if (items.ContainsKey(obj.Key))
                {
                    items[obj.Key] = obj.Value;
                }
                else
                    items.Add(obj.Key, obj.Value);
            }
        }

        public void Save(string fn)
        {
            using (var fs = new FileStream(cacheDir + fn, FileMode.OpenOrCreate, FileAccess.Write))
            {
                var bf = new BinaryFormatter();
                bf.Serialize(fs, items);
            }
        }

        public void Load(string fn)
        {
            using (var fs = new FileStream(cacheDir + fn, FileMode.Open, FileAccess.Read))
            {
                var bf = new BinaryFormatter();
                items = (Dictionary<string, object>)bf.Deserialize(fs);
            }
        }


        public void Set<TValue>(TValue val, string name)
        {
            this.items.Add(name, val);
        }

        public TValue Get<TValue>(string name, TValue @default)
        {
            if (!items.ContainsKey(name))
                return @default;
            return (TValue)items[name];
        }
    }
}
